<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">

		<title></title>
		<link rel="stylesheet" href="css/light-style.css"></link>
		<link rel="stylesheet" href="css/topic.css"></link>
		<link rel="stylesheet" href="css/vant.css"></link>
		<script src="js/dayjs.js"></script>
		<script src="js/dayjs_zh.js"></script>
		<script src="js/relativeTime.js"></script>
		<script src="js/uni.webview.js"></script>
		<script src="js/vue.min.js"></script>
		<script src="js/axios.js"></script>
		<script src="js/vant.js"></script>
		
	</head>
	<body>
		<div id="app" :style="showInput ? {paddingBottom: '0px'}:{ paddingBottom: '60px' }">
			
			<div class="topic">
				<div class="topic__header">
					{{ topic.title }}
				</div>
				<div class="topic__user">
					<img @click="handleUserInfoClick(topic.author.loginname)" class="topic__user-avatar" :src="topic.author.avatar_url"></img>
					<div class="topic__user-right">
						<div @click="handleUserInfoClick(topic.author.loginname)" class="topic__user-name">{{topic.author.loginname}}</div>
						<div class="topic__user-footer">
							<div class="topic__user-date">{{ createDate }}</div>
							<div v-if="vCount" class="topic__user-date topic__user-view">{{vCount}}人浏览过</div>
							<div v-if="coast" class="topic__user-date topic__user-view">预计阅读时间{{coast}}分钟</div>
						</div>
					</div>
				</div>
				<div class="topic__content" id="topicContent" v-html="topic.content"></div>
			</div>
			<div v-if="replyLength" class="topic-comments" ref="topicComments">
				<div class="topic-comments__title">评论({{replyLength}})</div>
					<comment-item v-for="item in replies" :key="item.id" :first="true" :reply="item" :topic="topic" :current-user="currentUser"/>
			</div>
			<div v-if="replyLength" class="topic-comments__all">
				<div class="topic-comments__line"></div>
				<span class="topic-comments__tips">已展示全部评论</span>
				<div class="topic-comments__line"></div>
			</div>
			<div class="topic__footer" :class="{ 'topic__footer-fixed': !showInput}">
				<input v-model="content" class="topic__footer-input" ref="input" @keydown.enter="handleSubmit" v-if="showInput" autofocus @blur="handleBlur"/>
				<div v-else class="topic__footer-input" @click="handleReplayClick()">
					<img src="icon/edit.png" alt="" srcset="" class="topic__footer-input-icon" />
					输入评论...
				</div>	
				<div class="topic__footer-reply" @click="handleMessageClick">
					<span class="topic__footer-reply-tag" v-if="topic.reply_count">{{replyLength}}</span>
					<img src="icon/reply.png" alt="" class="topic__footer-icon" />	
				</div>
				
				<img :src="topic.is_collect? 'icon/collected.png': 'icon/collect.png'" alt="" @click="handleCollectClick" class="topic__footer-icon"/>
			</div>
		</div>
	</body>
	<script type="text/html" id="commentItemTpl">
		<div class="topic-comments__wrap">
			<div class="topic-comments__item">
				<img class="topic-comments__avatar" @click="handleUserInfoClick(reply.author.loginname)" :src="reply.author.avatar_url"/>
				<div class="topic-comments__right">
					<div class="topic-comments__name" @click="handleUserInfoClick(reply.author.loginname)">{{reply.author.loginname}}
						<span v-if="topic.author.loginname === reply.author.loginname" class="topic-comments__author">作者</span>
					</div>
					<div class="topic-comments__content" v-html="reply.content"></div>
					<div class="topic-comments__footer">
						<div class="topic-comments__date">{{ formatDate(reply.create_at) }}</div>
						<div class="topic-comments__up">
							<img src="icon/reply.png" alt="" class="topic-comments__icon" @click="handleReplayClick(reply.id, reply.author)"/>
							<img @click="handleUpClick(reply.id)" v-if="reply.ups.indexOf(currentUser.id)" class="topic-comments__icon" :src="reply.is_uped? 'icon/good-fill.png':'icon/good.png'"/>
							{{ reply.ups.length || 0 }}
						</div>
					</div>
				</div>
			</div>
			<div v-if="reply.children && reply.children.length" :class="{ 'topic-comments__second':first }">
				<comment-item  v-for="item in reply.children" :key="item.id" :reply="item" :topic="topic" :current-user="currentUser"/>	
			</div>
		</div>
	</script>
	
	<script>
		dayjs.extend(dayjs_plugin_relativeTime);
		dayjs.locale('zh-cn')
		const request = axios.create({
		  baseURL: 'https://cnodejs.org/api/v1'
		});
		const urlSearchParams = new URLSearchParams(window.location.search)
		
		
		document.body.addEventListener("click",function(e){
			const target = e.target
		    if(target.tagName == 'A') {
				const href = target.getAttribute('href')
				 const isLink = /^(http|https):\/\/.*/.test(href)
				if(isLink) {
					console.log('打开外联...')
					uni.postMessage({
						data:{
							type: 'openLink',
							url: href
						},
						
					})
					 
				}else {
					const loginName = href.split('/')[2]
					uni.webView.navigateTo({
						url: '/pages/user-info/user-info?loginName='+loginName
					})
				}
				e.preventDefault()
			}
		})

		// 746f26fc-1009-4d2c-bc31-8a2464ce2aca
		const token = urlSearchParams.get('token')
		const topicId = urlSearchParams.get('topicId')
		
		 
		Vue.component('comment-item', {
			props: {
				reply: {
					type:Object,
					required: true
				},
				currentUser: {
					type:Object,
					required: true
				},
				topic: {
					type:Object,
					required: true
				},
				first: {
					type: Boolean,
					default: false
				}
			},
			mounted(){
				console.log(this.reply)
			},
			methods: {
				handleUserInfoClick(loginName){
					uni.postMessage({
						data:{
							type: 'userInfo',
							loginName: loginName
						},	
					})
				},
				formatDate(date){
					return dayjs(date).fromNow()
				},
			},
		  template: document.getElementById('commentItemTpl').innerHTML
		})
		
		var app = new Vue({
			el: '#app',
			data: {
				showInput: false,
				content: '',
				topic: {
					author:{},
					 
					content: ''
				},
				replies:[],
				currentUser:{
					 loginname: '' ,
					 id: '',
					 avatar_url: '',
				}
			},
			computed:{
				replyLength(){
					return (this.topic.replies || []).length ||0
				},
				vCount(){
					const count = this.topic.visit_count || 0
					if (count < 1000) {
						return count;
					}
					if (count < 10000) {
					    return (count / 1000).toFixed(1) + 'k';
					}  
					return (count / 10000).toFixed(1) + 'w';
				}, 
				coast(){
					const speed = 600; // 定义一分钟读60个字
					return Math.ceil(this.topic.content.length / speed)
				},
				createDate(){
					if(this.topic.create_at){
						return dayjs(this.topic.create_at).format('YYYY-MM-DD')
					}
				}
			},
			mounted(){
				this.fetchUserInfo()
				this.fetchTopicById()
				this.previewImage()
			},
			methods: {
				handleUserInfoClick(loginName){
					uni.postMessage({
						data:{
							type: 'userInfo',
							loginName: loginName
						},	
					})
				},
				handleMessageClick(){
					this.$refs.topicComments.scrollIntoView(true, {
						behavior:"smooth",
						block: 'center'
					});
				},
				renderImage(){
					const tags = document.getElementsByTagName("img")
					for(let tag of tags) {
						const src = tag.getAttribute('src')
						tag.onerror= () =>{
							tag.setAttribute('src', "icon/avatar.png")
						}
						const isLink = /^(http|https):\/\/.*/.test(src)
						if(isLink) {
							continue;
						}else{
							// if(src.startsWith('//gravatar.com/avatar/')){
							// 	tag.setAttribute('src', "icon/avatar.png")
							// }else 
							if(src.startsWith('//')) {
								tag.setAttribute('src', 'https:' + src)
							}	
						}
						
					}
				},
				previewImage() {
					document.getElementById('topicContent').addEventListener("click", function(e){
						const target = e.target
						if(target.tagName == 'IMG') {
							const src = target.getAttribute('src')
							uni.postMessage({
								data:{
									type: 'previewImage',
									url: src
								},	
							})
						}
					})
				},
				
				handleCollectClick(){
					if(!token) {
						vant.Toast('请登录');
						return 
					}
					const url = this.topic.is_collect ? '/topic_collect/de_collect' :'/topic_collect/collect'
					request({
						url,
						method: 'POST',
						data: { 
							accesstoken: token,
							topic_id:topicId  ,
						}
					}).then(ret => {
						if(ret.data.success) {
							this.fetchTopicById()
						}
					})
					
				},
				handleReplayClick(replyId){
					if(!token) {
						vant.Toast('请登录');
						return 
					}
					this.showInput = true
					this.replyId = replyId
					this.$nextTick(() =>{
						this.$refs.input.focus()
					})
					// uni.webView.navigateTo({
					// 	url: '/pages/reply/reply?replyId='+(replyId ||'')+"&loginname="+(((author ||{}).loginname) || '')
					// })
				},
				handleSubmit(){
					this.showInput = false
					const content = this.content; // 评论内容...
					const replyId = this.replyId
					request({
						url: '/topic/'+topicId+'/replies',
						method: 'post',
						data: {accesstoken: token, content : content, reply_id :replyId  }
					}).then(ret=> {
						if(ret.data.success) {
							this.fetchTopicById()
							this.replyId = ''
							this.content = ''	
						}
					})
				},
				handleBlur(){
					this.showInput = false
				},
				handleUpClick(replyId){
					if(!token) {
						vant.Toast('请登录');
						return 
					}
					request({
						url: '/reply/'+replyId+'/ups',
						method: 'POST',
						data: { 
							accesstoken: token,
						}
					}).then(ret => {
						if(ret.data.success) {
							this.fetchTopicById()
						}
					})
					
					
				},
				fetchUserInfo(){
					if(!token) {
						return 
					}
					request({
						url: '/accesstoken',
						method: 'POST',
						data: { accesstoken: token }
					}).then(ret=> {
						if(ret.data) {
							this.currentUser = ret.data
						}
					})
					
				},
				toReplyTree(){
					const list = this.topic.replies ||[]
					const arr = [];
					const map = {}
					list.forEach(i => map[i.id] = i)
					list.forEach((i) => {
						const reply_id = i.reply_id
						if(map[reply_id]) {
							map[reply_id].children = map[reply_id].children || []
							map[reply_id].children.push(i)
						}else {
							arr.push(i)
						}
					})
					this.replies = arr
				},
				fetchTopicById() {
					if(!topicId) {
						return 
					}
					request({
						url: '/topic/'+ topicId ,
						params: { accesstoken: token }
					}).then(res => {
						const ret =  res.data
						if(ret.success) {
							this.topic = ret.data
							// 把 回复的评论数组转成树
							this.toReplyTree()
							this.$nextTick(this.renderImage)
						}
					})
				}
			},
		})
	</script>
</html>